'use strict';
var Oauth = require('co-wechat-oauth');
module.exports = app => {
  class HomeController extends app.Controller {
    * index(ctx) {
        // indexvar oauthApi = new Oauth('wx8b26863a1b712d2c','d96487ac300de900e06af18975b9d612',async function (openid) {
        //     var user= await this.model.User.findOne({where:{openid:openid}});
        //     return user.token;
        // },async function (openid,token) {
        //     var user= await this.model.User.findOne({where:{openid:openid}});
        //     if(user){
        //         await this.model.User.update({
        //             token:token
        //         },{
        //             where:{openid:openid}
        //         })
        //     }
        // });
        var client = new Oauth(ctx.session.wechat.appId,ctx.session.wechat.appSecret);
        var code=ctx.request.query.code;
        const state=ctx.request.query.state;
        var token=yield client.getAccessToken(code);

        var accesstoken=token.data.access_token;
		
        var openid = token.data.openid;
        var userInfo = yield client.getUser(openid);
		console.log(userInfo);
		var user = yield ctx.model.User.findOne({where:{openid:openid}});
		
        if(user){
			console.log("update");
          var update=yield ctx.model.User.update({
            subscribe:userInfo.subscribe,
              nickname:userInfo.nickname,
              sex:userInfo.sex,
              city:userInfo.city,
              country:userInfo.country,
              province:userInfo.province,
              headimgurl:userInfo.headimgurl,
              subscribeTime:userInfo.subscribe_time,
              remark:userInfo.remark,
              groupid:userInfo.groupid,
              tagidList:userInfo.tagid_list
          },{
            where:{openid:openid}
          });
          user = yield ctx.model.User.findOne({where:{openid:openid}});
        }else {
            var create=yield ctx.model.User.create({
                openid:userInfo.openid,
                subscribe:userInfo.subscribe,
                nickname:userInfo.nickname,
                sex:userInfo.sex,
                city:userInfo.city,
                country:userInfo.country,
                province:userInfo.province,
                headimgurl:userInfo.headimgurl,
                subscribeTime:userInfo.subscribe_time,
                remark:userInfo.remark,
                groupid:userInfo.groupid,
                tagidList:userInfo.tagid_list,
				wechatId:ctx.session.wechat.id
            });
			console.log(create);
            user=create;
        }
        ctx.session.user=user;
        console.log('--------用户信息----------');
        console.log(ctx.session.user.id);
        console.log(ctx.session.user.nickname);
        console.log(ctx.session.user.openid);
        console.log('-------------------------');
		console.log("state",state);
        this.ctx.redirect(state); 
    }
  }
  return HomeController;
};
